import * as API from "@/api";
import {
  getSessionObjStore,
  setSessionObjStore,
  setSessionStore,
  getSessionStore,
  setCookie,
  getCookie,
  setCookieObj,
  getCookieObj
} from "@/libs/util";

export default {
  state: {
    userInfo: getCookieObj("userInfo") ? getCookieObj("userInfo") : "",
    token: getCookie("token"),
    access: getCookie("access"),
    messageCount: 0
  },
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
      setCookieObj("userInfo", userInfo);
    },
    setAccess(state, access) {
      state.access = access;
      setCookie("access", access);
    },
    setToken(state, token) {
      state.token = token;
      setCookie("token", token);
    }
  },
  actions: {
    //重置权限
    handleAccess({ commit }, value) {
      commit("setAccess", value);
    },

    // 登录
    handleLogin({ state, commit }, obj) {
      return new Promise((resolve, reject) => {
        API.login(obj)
          .then(res => {
            const data = res.data;
            commit("setToken", data.userName);
            commit("setAccess", data.access.toString());
            commit("setUserInfo", data);
            resolve(data);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    // 退出登录
    handleLogOut({ state, commit }) {
      return new Promise((resolve, reject) => {
        API.logout(state.token)
          .then(() => {
            commit("setUserInfo", "");
            commit("setToken", "");
            commit("setAccess", "");
            resolve();
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    //客户端单方面退出
    handleClientLogOut({ state, commit }) {
      commit("setUserInfo", "");
      commit("setToken", "");
      commit("setAccess", "");
    },
    // 修改密码
    editUserPw({ state, commit }, obj) {
      return new Promise((resolve, reject) => {
        API.editPW(obj)
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    }
  }
};
